import { useHistory, useLocation } from 'react-router-dom'
import { NavBar } from 'antd-mobile'

import styles from './index.module.scss'
import { useEffect, useRef } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getSearchResult } from '@/store/acitons/search'
import { RootState } from '@/types/store'
import ArticleItem from '@/pages/Home/components/ArticleItem'
import { InfiniteScroll } from 'antd-mobile'
const Result = () => {
  const history = useHistory()
  const location = useLocation()
  const dispatch = useDispatch()
  // console.log(location)
  const keyword = decodeURI(location.search.replace('?keyword=', ''))
  console.log(keyword)
  // 2. 根据传递过来的参数 关键字搜索内容
  useEffect(() => {
    dispatch(getSearchResult(keyword))
  }, [dispatch, keyword])
  // 3. 从redux 中获取数据 搜索额
  const {
    searchResult: { results = [] },
  } = useSelector((state: RootState) => state.history)
  // 4. 处理滚动
  const pageRef = useRef(1)
  const hasMore = true
  const loadMore = async () => {
    await dispatch(getSearchResult(keyword, pageRef.current))
    pageRef.current++
  }
  return (
    <div className={styles.root}>
      <NavBar onBack={() => history.go(-1)}>搜索结果</NavBar>
      <div className="article-list">
        {results.map((item, index) => {
          return (
            <div className="article-item" key={index}>
              <ArticleItem article={item}></ArticleItem>
            </div>
          )
        })}
        <InfiniteScroll hasMore={hasMore} loadMore={loadMore}></InfiniteScroll>
      </div>
    </div>
  )
}

export default Result
